package com.genesis.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.genesis.mall.entity.UmsAdmin;
import com.genesis.mall.exception.LoginException;
import com.genesis.mall.mapper.UmsAdminMapper;
import com.genesis.mall.service.IUmsAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.genesis.mall.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements IUmsAdminService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UmsAdminMapper adminMapper;
    @Override
    public String login(String username, String password) {
        //用户登录
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        LambdaQueryWrapper<UmsAdmin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsAdmin::getUsername, username);
        UmsAdmin umsadmin = this.getOne(lqw);
        if (umsadmin == null) {
            throw new LoginException("用户名不存在");
        } else if (!bCryptPasswordEncoder.matches(password, umsadmin.getPassword())) {
            throw new LoginException("密码错误");
        } else if (umsadmin.getStatus() != 1) {
            throw new LoginException("账号已经冻结");
        }
        //修改该账号的登录时间
        umsadmin.setLoginTime(LocalDateTime.now());
        this.updateById(umsadmin);
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("adminId",umsadmin.getId());
        String uuid = UUID.randomUUID().toString();
        tokenMap.put("uuid",uuid);
        String token = TokenUtil.getToken(tokenMap);
        //将token放入redis中
        redisTemplate.opsForValue().set("Bearer_"+uuid,token,360000l, TimeUnit.SECONDS);
        return token;
    }

    @Override
    public List<String> getAdmin() {
        return adminMapper.getAdmin();
    }
}
